﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace SocketService
{
    public partial class frmMain : Form
    {
        Socket socketService;//实例化一个套接字对象
        Dictionary<string, Socket> socketClients = new Dictionary<string, Socket>();
        Thread threadList;
        public frmMain()
        {
            InitializeComponent();
        }

        private void btnLink_Click(object sender, EventArgs e)
        {
            IPAddress ipAddress = IPAddress.Parse(txtIP.Text.Trim());
            int port = int.Parse(txtPort.Text.Trim());
            EndPoint endPoint = new IPEndPoint(ipAddress, port);
            try
            {
                ricServerMess.Text += "开始绑定服务器:" + txtIP.Text.Trim() + ":" + txtPort.Text.Trim() + "\n";
                if (socketService==null)
                {
                    socketService = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
                    socketService.Bind(endPoint);//绑定到指定的端口
                    socketService.Listen(10);
                }
                ricServerMess.Text += "绑定成功!\n";
                ricServerMess.Text += "开始监听......\n";

                if (!threadList.IsAlive)
                {
                    threadList.Start();
                }
                btnStop.Enabled = true;
                btnLink.Enabled = false;
            }
            catch (Exception)
            {
                ricServerMess.Text += "监听端口失败,请联系管理员!\n";
            }
        }
        private void RefreshDictionary()
        {
            while (true)
            {
                if (socketService == null)
                {
                    Thread.Sleep(200);
                    continue;
                }
                try
                {
                    var client = socketService.Accept();
                    string clientIp = client.RemoteEndPoint.ToString();
                    if (!socketClients.ContainsKey(clientIp))
                    {
                        socketClients.Add(clientIp, client);
                        StartReceive(clientIp, client);
                    }
                }
                catch (Exception)
                {
                    if (ricClientMessage.InvokeRequired)
                    {
                        ricClientMessage.Invoke(new Action(() =>
                        {
                            ricClientMessage.Text += "服务已关闭!\n";
                        }));
                    }
                }
                Thread.Sleep(200);
            }
        }
        private void StartReceive(string key, Socket socketClient)
        {
            ThreadPool.QueueUserWorkItem(new WaitCallback(o =>
            {
                byte[] buffer = new byte[1024];//实例化一个接收数据的缓冲区
                if (ricClientMessage.InvokeRequired)
                {
                    ricClientMessage.Invoke(new Action(() =>
                    {
                        ricClientMessage.Text += key + " 开启接收数据了\n";
                    }));
                }
                while (socketClient.Connected)
                {
                    try
                    {
                        int length = socketClient.Receive(buffer);//接收数据并存放到缓冲区内
                        string str = Encoding.UTF8.GetString(buffer, 0, length);//将信息转换成数据
                        if (ricClientMessage.InvokeRequired)
                        {
                            ricClientMessage.Invoke(new Action(() =>
                            {
                                ricClientMessage.Text += string.Format("{0}: {1}", key, str);
                            }));
                        }
                        Thread.Sleep(50);
                    }
                    catch (Exception)
                    {
                        if (ricClientMessage.InvokeRequired)
                        {
                            ricClientMessage.Invoke(new Action(() =>
                            {
                                ricClientMessage.Text += string.Format("客户端{0}断开了连接\n", key);
                            }));
                        }
                        socketClient.Close();
                        socketClients.Remove(key);
                    }
                }
            }));
        }
        private void ricMessage_KeyUp(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                foreach (var socketClient in socketClients)
                {
                    if (string.IsNullOrEmpty(ricMessage.Text.Trim()))
                    {
                        return;
                    }
                    if (socketClient.Value.Connected)
                    {
                        byte[] buffer = Encoding.UTF8.GetBytes(ricMessage.Text);
                        socketClient.Value.Send(buffer);
                    }
                    else
                    {
                        socketClients.Remove(socketClient.Key);
                    }
                }
                ricMessage.Text = "";
            }
        }

        private void btnStop_Click(object sender, EventArgs e)
        {
            socketService.Close();
            socketService = null;
            socketClients.Clear();
            btnStop.Enabled = false;
            btnLink.Enabled = true;
        }

        private void frmMain_Load(object sender, EventArgs e)
        {
            threadList = new Thread(RefreshDictionary);
            threadList.IsBackground = true;
        }
    }
}
